package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import modl.Blog;
import modl.BlogDao;
import modl.User;
import modl.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-03-25
 * Time: 19:58
 */
@WebServlet("/author")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId = req.getParameter("blogId");
        if(blogId == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("参数非法,缺少blogId");
            return;
        }
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectById(Integer.parseInt(blogId));
        if(blog == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("没有找到指定博客:blogId = "+blogId);
            return;
        }
        UserDao userDao = new UserDao();
        User author = userDao.selectById(blog.getUserId());
        String respJson = objectMapper.writeValueAsString(author);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);

    }
}
